package com.sweet.fourtimeoa.controller;

import com.sweet.fourtimeoa.mapper.UserMapper;
import com.sweet.fourtimeoa.pojo.vo.LoginVo;

import com.sweet.fourtimeoa.pojo.entity.Users;
import com.sweet.fourtimeoa.properties.JwtProperties;
import com.sweet.fourtimeoa.service.UserService;
import com.sweet.fourtimeoa.util.BaseContext;
import com.sweet.fourtimeoa.util.JwtUtil;
import com.sweet.fourtimeoa.util.Result;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Tag(name = "登录模块")
@RestController
@RequestMapping
@CrossOrigin(origins = "*")
public class LoginController {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result<LoginVo> login(String username, String password){
        log.info("用户名:{},密码:{}",username,password);
        // 1,判断账号密码是否正确
        Users user = userService.login(username);
       if (user==null){
           return Result.error("密码错误");
       }
       Integer status = user.getStatus();
       if ( status == 0){
           return Result.error("账号已禁用");
       }
       String passwordHash = user.getPasswordHash();
       if (!password.equals(passwordHash)){
           return Result.error("账号或密码错误");
       }
       BaseContext.setCurrentId(Long.valueOf(user.getUserId()));
        Map<String,Object> claims = new HashMap<>();
       claims.put("userId",user.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminKey(), jwtProperties.getTtl(), claims);
        LoginVo loginVo = LoginVo.builder()
                .id(user.getUserId())
                .username(user.getUsername())
                .roleId(user.getRoleId())
                .realName(user.getRealName())
                .departmentId(user.getDepartmentId())
                .departmentName(userService.getUserByName(username))
                .title(user.getTitle())
                .token(token)
                .build();
        return Result.success(loginVo);
    }

    @Operation( summary = "退出登录")
    @GetMapping("/logout")
    public Result logout(){
        return Result.success("成功");
    }
}
